package 暑假实习面试.腾讯面试题;

import java.util.Arrays;
import java.util.Scanner;

public class No3 {

    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);

        while (input.hasNext()){
            int count=input.nextInt();

            for (int i = 0; i < count; i++) {

                int length=input.nextInt();
                int maxTime=0;
                int[] arr=new int[length];

                for (int j = 0; j < length; j++) {
                    int time=input.nextInt();
                    maxTime=Math.max(maxTime,time);
                    arr[j]=input.nextInt();
                }

                Arrays.sort(arr);

                int sum=0;
                for (int j = arr.length-1; j >= 0&&maxTime>0; j--) {
                    sum+=arr[j];
                    maxTime--;
                }

                System.out.println(sum);

            }
        }

    }

}
